package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tbit.common.utils.MessageUtil;
import com.tbit.main.constant.*;
import com.tbit.main.constant.enums.PerformanceBizType;
import com.tbit.main.controller.interceptor.LoginUserContextHolder;
import com.tbit.main.dao.core.*;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.pojo.VO.LongOrderTimeVO;
import com.tbit.main.pojo.maintain_performance.config.DispatchPerformanceConfig;
import com.tbit.main.pojo.maintain_performance.config.PowerChangePerformanceConfig;
import com.tbit.main.pojo.maintain_performance.rule.LowPowerRule;
import com.tbit.main.pojo.maintain_performance.rule.UnusedTimeBasedRule;
import com.tbit.main.service.*;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.GeoUtil;
import com.tbit.main.util.LogUtil;
import com.tbit.main.util.RandomPointUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 设备管理
 *
 * @author Leon
 * 2019年10月16日 下午8:08:40
 */
@Slf4j
@Service("machineManagerService")
public class MachineManagerServiceImpl implements MachineManagerService {
    @Autowired
    private MachineBorrowService machineBorrowService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private MachineAbnormalService machineAbnormalService;
    @Autowired
    private MachineFaultService machineFaultService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private BatteryModelService batteryModelService;
    @Autowired
    private MachineOccupyService machineOccupyService;
    @Autowired
    private GeoreGionService georeGionService;
    @Autowired
    private BatteryMachineService batteryMachineService;
    @Autowired
    private MachineNoIncomeService machineNoIncomeService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private DataService dataService;
    @Autowired
    private StockMachineService stockMachineService;
    @Autowired
    private DetentionMachineBoundService detentionMachineBoundService;
    @Autowired
    private DevicePriorityService devicePriorityService;
    @Autowired
    private UserService userService;
    @Autowired
    private MQProducer mqProducer;
    @Autowired
    private VerticalParkLogService verticalParkLogService;
    @Autowired
    private AccountConfigDao accountConfigDao;
    @Autowired
    private MachineSuperviseDao machineSuperviseDao;
    @Autowired
    private MachineDao machineDao;
    @Autowired
    private RoleConfigService roleConfigService;
    @Autowired
    private PerformanceRuleGroupService ruleGroupService;
    @Autowired
    private MachineTagDao machineTagDao;
    @Resource
    private AccountConfigExtDao accountConfigExtDao;

    @Override
    public List<MachineStatusBorrow> getAll(AccountUser accountUser, Integer accountId, Integer mapType, List<Integer> regionId) {
        List<MachineStatusBorrow> machineStatusBorrows = new ArrayList<>();

        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses;
        if (CollUtil.isEmpty(regionId)) {
            machineStatuses = machineStatusService.getByAccountId(accountId);
        } else {
            machineStatuses = machineStatusService.getByRegionIds(regionId);
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatuses)) {
            return Collections.emptyList();
        }

        /**查询正在借用设备*/
        List<MachineBorrow> machineBorrows;
        if (CollUtil.isEmpty(regionId)) {
            machineBorrows = machineBorrowService.getByAccountId(accountId);
        } else {
            machineBorrows = machineBorrowService.getByRegionId(regionId);
        }
        List<Integer> machineBorrowsIds = machineBorrows.stream().map(MachineBorrow::getMachineId).collect(Collectors.toList());

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineBorrowsIds.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> delIdsMachine = devicePriorityService.checkPriority(machineBorrowsIds, accountId, DevicePriorityConstant.DEVICEPRIORITY_QXZ);
            machineBorrowsIds = machineBorrowsIds.stream().filter(machineStatus -> !delIdsMachine.contains(machineStatus)).collect(
                    Collectors.toList());
        }

        /**查询所有异常设备*/
        List<Integer> machineAbnormalMap;
        /**异常类型：车辆id*/
        Map<Integer, List<Integer>> machineAbnormalTypeMap = new HashMap<Integer, List<Integer>>();
        List<MachineAbnormal> machineAbnormals;
        if (CollUtil.isEmpty(regionId)) {
            machineAbnormals = machineAbnormalService.groupMachineIdAndType(accountId, null, null);
        } else {
            machineAbnormals = machineAbnormalService.groupMachineIdAndRegionId(regionId, null, null);
        }

        machineAbnormalMap = machineAbnormals.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toList());

        /**车辆功能优先级逻辑判断*/
        if (!machineAbnormals.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            machineAbnormalMap.clear();
            for (MachineAbnormal ma : machineAbnormals) {
                if (machineAbnormalTypeMap.containsKey(ma.getAbnormalType())) {
                    machineAbnormalTypeMap.get(ma.getAbnormalType()).add(ma.getMachineId());
                } else {
                    List<Integer> machineIds = new LinkedList<>();
                    machineIds.add(ma.getMachineId());
                    machineAbnormalTypeMap.put(ma.getAbnormalType(), machineIds);
                }
            }

            if (CollUtil.isNotEmpty(machineAbnormals)) {
                machineAbnormals = getAbnormalTypeDelMachineAbnormal(machineAbnormals, accountId, regionId);
                machineAbnormalMap = machineAbnormals.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toList());
            }
        }

        List<MachineFault> machineFaults;
        if (CollUtil.isEmpty(regionId)) {
            machineFaults = machineFaultService.getByAccountId(accountId);
        } else {
            machineFaults = machineFaultService.getByRegionId(regionId);
        }

        List<Integer> machineFaultsIds = machineFaults.stream().filter(machineFault -> {
            //过滤掉疑似故障
            return !Objects.equals(machineFault.getFrom(),4);
        }).map(MachineFault::getMachineId).collect(Collectors.toList());
        //疑似故障
        List<Integer> suspectedFaultIdList = machineFaults.stream().filter(machineFault -> {
            return Objects.equals(machineFault.getFrom(), 4);
        }).map(MachineFault::getMachineId).collect(Collectors.toList());

        /**车辆功能优先级逻辑判断*/
        if (!machineFaults.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            machineFaultsIds.clear();
            /**返回数据*/
            List<MachineFault> faults = new ArrayList<>();
            List<MachineFault> ywFault = machineFaults.stream().filter(machineStatusFault -> machineStatusFault.getFrom() == 0).collect(
                    Collectors.toList());
            List<MachineFault> yhFault = machineFaults.stream().filter(machineStatusFault -> machineStatusFault.getFrom() == 1).collect(
                    Collectors.toList());
            /**运维异常校验*/
            List<Integer> ywMachineIds = ywFault.stream().map(MachineFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(ywMachineIds)) {
                List<Integer> delIds = devicePriorityService.checkPriority(ywMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YWGZ);
                ywFault = ywFault.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**用户异常校验*/
            List<Integer> yhMachineIds = yhFault.stream().map(MachineFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(ywMachineIds)) {
                List<Integer> yhdelIds = devicePriorityService.checkPriority(yhMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YHGZ);
                yhFault = yhFault.stream().filter(machineStatus -> !yhdelIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**求并集*/
            faults.addAll(ywFault);
            faults.addAll(yhFault);
            machineFaultsIds = faults.stream().map(MachineFault::getMachineId).collect(Collectors.toList());
        }

        /**获取电池编号*/
        List<BatteryMachine> batteryMachineList;
        if (CollUtil.isEmpty(regionId)) {
            batteryMachineList = batteryMachineService.getByAccountId(accountId);
        } else {
            batteryMachineList = batteryMachineService.getByRegionIds(regionId);
        }
        Map<Integer, String> batteryMachineMap = new HashMap<>();
        for (BatteryMachine batteryMachine : batteryMachineList) {
            batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
        }

        // 库存车辆
        List<StockMachine> stockMachines = stockMachineService.getByAccountId(accountId, regionId);
        List<Integer> stockMachineIds = stockMachines.stream().map(StockMachine::getMachineId).collect(Collectors.toList());

        // 扣押车辆
        List<DetentionMachineBound> detentionMachineBounds = detentionMachineBoundService.getListByAccount(accountId);
        List<Integer> detentionMachineMachineIds = detentionMachineBounds.stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

        for (MachineStatus ms : machineStatuses) {
            MachineStatusBorrow msb = new MachineStatusBorrow();

            /**是否使用中*/
            msb.setIsUse(machineBorrowsIds.contains(ms.getMachineId()));

            /**是否异常*/
            msb.setIsAbnormal(machineAbnormalMap.contains(ms.getMachineId()));

            /**是否故障*/
            msb.setIsFault(machineFaultsIds.contains(ms.getMachineId()));

            /** 库存状态 */
            msb.setStock(stockMachineIds.contains(ms.getMachineId()));

            /** 扣押状态 */
            msb.setDetention(detentionMachineMachineIds.contains(ms.getMachineId()));

            /**疑似故障*/
            msb.setSuspectedFault(suspectedFaultIdList.contains(ms.getMachineId()));

            msb.setMachineId(ms.getMachineId());
            msb.setMachineNO(ms.getMachineNO());
            msb.setLon(ms.getLon());
            msb.setLat(ms.getLat());
            msb.setPosDt(ms.getPosDt());
            msb.setBatDt(ms.getBatDt());
            msb.setSocPercent(ms.getSocPercent());
            msb.setSurplusMileage(ms.getSurplusMileage());
            msb.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
            msb.setState(ms.getState());
            machineStatusBorrows.add(msb);
        }

        /**校准*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            calibrateService.celibrateMachineStatusBorrow(machineStatusBorrows, mapType);
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<Integer, Machine>();
            List<Integer> exitMachineIdList = new ArrayList<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
                exitMachineIdList.add(machine.getMachineId());
            }
            machineStatusBorrows = machineStatusBorrows.stream().filter(machineStatusBorrow -> {
                return exitMachineIdList.contains(machineStatusBorrow.getMachineId());
            }).collect(Collectors.toList());
            for (MachineStatusBorrow ms : machineStatusBorrows) {
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setMachineType(machine.getMachineType());
                }
            }
        }

        // 运维绩效推荐气泡
        AccountConfigExt dispatchPerfSwitch = dataService.getAccountidExt(accountId + AccountConfigExtConstant.DISPATCH_PERFORMANCE);
        if (dispatchPerfSwitch != null && dispatchPerfSwitch.getParamValue().equals("1")) {
            // 优先级：异常>车辆标签>闲置
            // 按优先级低到高计算，这样高优先级的气泡就会覆盖掉低优先级的气泡
            DispatchPerformanceConfig config = ruleGroupService.selectBizPerformanceConfig(accountId, DispatchPerformanceConfig::fromRaw, PerformanceBizType.DISPATCH);

            // 先计算闲置时长
            if (config.getUnusedTimeBased() != null && config.getUnusedTimeBased().getEnabled()) {
                List<UnusedTimeBasedRule> subRules = config.getUnusedTimeBased().getSubRules();
                for (MachineStatusBorrow ms : machineStatusBorrows) {
                    if (ms.getLastBorrowTime() == null)
                        continue;
                    Date lastBorrowTime = DateUtil.parse(ms.getLastBorrowTime());
                    for (UnusedTimeBasedRule subRule : subRules) {
                        if (subRule.getUnusedTime().match((int) DateUtil.between(lastBorrowTime, new Date(), DateUnit.HOUR))) {
                            ms.setPerformanceToast(subRule.getPriority());
                            break;
                        }
                    }
                }
            }

            // 再计算车辆标签
            if (config.getTagSolved() != null && config.getTagSolved().getEnabled()) {
                // 获取车辆标签
                List<Integer> machineIds = machineStatusBorrows.stream()
                        .map(MachineStatusBorrow::getMachineId)
                        .collect(Collectors.toList());
                Map<Integer, List<MachineTag>> machineTags = machineTagDao.getMachineTagByMachineId(machineIds).stream()
                        .collect(Collectors.groupingBy(MachineTag::getMachineId));

                // 标签规则
                Set<Long> tagIds = config.getTagSolved().getSubRules().stream()
                        .flatMap(rule -> rule.getTagIds().stream())
                        .collect(Collectors.toSet());

                for (MachineStatusBorrow ms : machineStatusBorrows) {
                    List<MachineTag> machineTagList = machineTags.get(ms.getMachineId());
                    if (CollUtil.isNotEmpty(machineTagList)) {
                        for (MachineTag machineTag : machineTagList) {
                            if (tagIds.contains(machineTag.getTagId())) {
                                ms.setPerformanceToast(4);
                                break;
                            }
                        }
                    }
                }
            }

            // 最后计算异常
            if (config.getAbnormalSolved() != null && config.getAbnormalSolved().getEnabled()) {
                // 设备异常表
                Map<Integer, List<Integer>> machineId2Abnormal = new HashMap<>();
                for (MachineAbnormal machineAbnormal : machineAbnormals) {
                    machineId2Abnormal.computeIfAbsent(machineAbnormal.getMachineId(), k -> new ArrayList<>())
                            .add(machineAbnormal.getAbnormalType());
                }

                // 异常规则
                Set<Integer> abnormalTypes = config.getAbnormalSolved().getSubRules().stream()
                        .flatMap(rule -> rule.getAbnormalTypes().stream())
                        .collect(Collectors.toSet());

                for (MachineStatusBorrow ms : machineStatusBorrows) {
                    if (!machineId2Abnormal.containsKey(ms.getMachineId()))
                        continue;
                    for (Integer abnormalType : machineId2Abnormal.get(ms.getMachineId())) {
                        if (abnormalTypes.contains(abnormalType)) {
                            ms.setPerformanceToast(3);
                            break;
                        }
                    }
                }
            }
        }

        /*设置超时长订单时间*/
        if (CollectionUtil.isNotEmpty(machineStatusBorrows)) {
            Map<Integer, String> longOrderTime = getLongOrderTime(machineStatusBorrows.stream().map(MachineStatusBorrow::getMachineId).collect(Collectors.toList()), accountId);
            if (CollectionUtil.isNotEmpty(longOrderTime)) {
                for (MachineStatusBorrow ms : machineStatusBorrows) {
                    ms.setLongOrderHour(longOrderTime.getOrDefault(ms.getMachineId(), ""));
                }
            }
        }

        return machineStatusBorrows;
    }

    private static final ReentrantLock REENTRANT_LOCK = new ReentrantLock();

    @Override
    public List<Integer> selectSuperviseMachine(Integer roleId, Integer accountId) {
        List<Integer> machineIdList = new LinkedList<>();
        //根据唯一索引获取账号绑定的角色
        if (roleId != null) {
            RoleConfig roleConfig = roleConfigService.getRoleKey(roleId, RoleConfigConstant.SUPERVISE_MACHINE);
            if (roleConfig == null || Objects.equals(0, roleConfig.getParamValue())) {
                return machineIdList;
            }
            //如果是监管人员
            AccountConfig accountConfig = accountConfigDao.getByAccountId(accountId);
            int virtualCarNum = accountConfig == null ? 0 : accountConfig.getVirtualCarNum() == null ? 0 : accountConfig.getVirtualCarNum();
            if (virtualCarNum == 0) {
                //如果为0或者没配置，默认全部车辆都不给看
                machineIdList.add(-2);
                return machineIdList;
            }
            try {
                //防止两个接口第一次同时请求往监管人员绑定车辆表重复插入数据
                REENTRANT_LOCK.lock();
                LambdaQueryWrapper<MachineSupervise> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(MachineSupervise::getAccountId, accountId);
                machineIdList = machineSuperviseDao.selectList(queryWrapper)
                        .stream().map(MachineSupervise::getMachineId).collect(Collectors.toList());
                if (machineIdList.size() != virtualCarNum) {
                    List<Integer> allMachineId = machineDao.getByAccountId(accountId).stream().map(Machine::getMachineId).collect(Collectors.toList());
                    machineIdList = chooseReturnMachines(allMachineId, virtualCarNum);
                    List<MachineSupervise> machineSuperviseList = new LinkedList<>();
                    Date date = new Date();
                    machineSuperviseDao.deleteById(accountId);
                    for (Integer id : machineIdList) {
                        machineSuperviseList.add(new MachineSupervise(id, accountId, date));
                    }
                    machineSuperviseDao.insertBatch(machineSuperviseList);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                REENTRANT_LOCK.unlock();
            }
        }
        return machineIdList;
    }

    List<Integer> chooseReturnMachines(List<Integer> machines, Integer virtualCarNum) {
        int machineSize = machines.size();
        virtualCarNum = machineSize > virtualCarNum ? virtualCarNum : machineSize;
        if (machineSize == virtualCarNum) {
            return machines;
        }
        List<Integer> newMachineList = new LinkedList<>();
        for (int i = 0, j = machineSize - 1, count = 0; i < j; i++, j--, count += 2) {
            newMachineList.add(machines.get(i));
            if (newMachineList.size() == virtualCarNum) {
                break;
            }
            newMachineList.add(machines.get(j));
            if (newMachineList.size() == virtualCarNum) {
                break;
            }
        }
        return newMachineList;
    }


    @Override
    public List<MachineStatus> getByPower(AccountUser accountUser, Integer accountId, Integer soc, Integer mapType, List<Integer> regionId, Integer startSoc, Integer endSoc) {
        List<MachineStatus> machineStatus;
        if (startSoc != null) {
            if (CollUtil.isEmpty(regionId)) {
                machineStatus = machineStatusService.getSocByKey(accountId, startSoc, endSoc);
            } else {
                machineStatus = machineStatusService.getSocByRegionIdAndKey(regionId, startSoc, endSoc);
            }
        } else {
            if (CollUtil.isEmpty(regionId)) {
                machineStatus = machineStatusService.getSocByAccountId(accountId, soc);
            } else {
                machineStatus = machineStatusService.getSocByRegionId(regionId, soc);
            }
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatus = machineStatus.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatus)) {
            return Collections.emptyList();
        }
        /** 校准 */
        if (CollUtil.isNotEmpty(machineStatus)) {
            /**校准*/
            calibrateService.celibrateMachineStatus(machineStatus, mapType);

            /** 查询当前在使用车辆 */
            Map<Integer, MachineBorrow> machineBorrowMap = new HashMap<>();
            List<MachineBorrow> machineBorrows;
            if (CollUtil.isEmpty(regionId)) {
                machineBorrows = machineBorrowService.getByAccountId(accountId);
            } else {
                machineBorrows = machineBorrowService.getByRegionId(regionId);
            }
            for (MachineBorrow mb : machineBorrows) {
                machineBorrowMap.put(mb.getMachineId(), mb);
            }

            /**查询电池方案*/
            Map<Integer, Integer> machineBatteryMap = new HashMap<>();
            List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
            for (MachineBatteryModel mbm : machineBatterys) {
                machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
            }

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList;
            if (CollUtil.isEmpty(regionId)) {
                batteryMachineList = batteryMachineService.getByAccountId(accountId);
            } else {
                batteryMachineList = batteryMachineService.getByRegionIds(regionId);
            }
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            List<Integer> machineIdDD = new LinkedList<>();

            AccountConfig accountConfig = dataService.getAccountConfig(accountId);

            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            // 运维绩效气泡推荐
           AccountConfigExt powerChangePerfSwitch = dataService.getAccountidExt(accountId + AccountConfigExtConstant.POWER_CHANGE_PERFORMANCE);
           if (powerChangePerfSwitch != null && !powerChangePerfSwitch.getParamValue().equals("0")) {
               // 换电常规方案
               if (powerChangePerfSwitch.getParamValue().equals("1")) {
                   PowerChangePerformanceConfig pcConfig = ruleGroupService.selectBizPerformanceConfig(accountId, PowerChangePerformanceConfig::fromRaw, PerformanceBizType.POWER_CHANGE_CONVENTION);
                   // 匹配电量气泡
                    if (pcConfig.getLowPowerBased() != null && pcConfig.getLowPowerBased().getEnabled()) {
                        List<LowPowerRule> lowPowerRules = pcConfig.getLowPowerBased().getSubRules();
                        for (MachineStatus ms : machineStatus) {
                            if (ms.getSocPercent() == null)
                                continue;
                            for (LowPowerRule lowPowerRule : lowPowerRules) {
                                if (lowPowerRule.getBeforeChangePower().match(ms.getSocPercent())) {
                                    ms.setPerformanceToast(lowPowerRule.getPriority());
                                    break;
                                }
                            }
                        }
                    }
               }
               // 换电站点优先方案
               if (powerChangePerfSwitch.getParamValue().equals("2")) {
                   PowerChangePerformanceConfig pcConfig = ruleGroupService.selectBizPerformanceConfig(accountId, PowerChangePerformanceConfig::fromRaw, PerformanceBizType.POWER_CHANGE_STATION);
                   if (pcConfig.getStationPriorityBased() != null && pcConfig.getStationPriorityBased().getEnabled()) {
                       for (MachineStatus ms : machineStatus) {
                           if (ms.getLevel() == null)
                               continue;

                           ms.setPerformanceToast(ms.getLevel() + 2); // 站点等级 + 2 = 气泡枚举
                           break;
                       }
                   }
               }
           }

            for (MachineStatus ms : machineStatus) {
                if (ms.getSocPercent() <= accountConfig.getBorrowSocLimit()) {
                    machineIdDD.add(ms.getMachineId());
                }
                if (machineBorrowMap.containsKey(ms.getMachineId())) {
                    ms.setInUse(1);
                } else {
                    ms.setInUse(0);
                }
                Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
                ms.setBatteryModelId(batteryModelId);
                ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));
            }

            AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
            /**车辆功能优先级逻辑判断*/
            if (!machineIdDD.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
                List<Integer> delIds = devicePriorityService.checkPriority(machineIdDD, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_DD);
                machineStatus = machineStatus.stream().filter(machineStatu -> !delIds.contains(machineStatu.getMachineId())).collect(
                        Collectors.toList());
            }

        }
        return machineStatus;
    }

    @Override
    public List<MachineStatus> getByMachineId(Integer accountId, List<Integer> machineIdList, Integer mapType) {
        List<MachineStatus> machineStatus = machineStatusService.getByMachineIdBatch(machineIdList);

        /** 校准 */
        if (CollUtil.isNotEmpty(machineStatus)) {
            /**校准*/
            calibrateService.celibrateMachineStatus(machineStatus, mapType);

            /** 查询当前在使用车辆 */
            Map<Integer, MachineBorrow> machineBorrowMap = new HashMap<Integer, MachineBorrow>();
            List<MachineBorrow> machineBorrows = machineBorrowService.getByAccountId(accountId);
            for (MachineBorrow mb : machineBorrows) {
                machineBorrowMap.put(mb.getMachineId(), mb);
            }

            /**查询电池方案*/
            Map<Integer, Integer> machineBatteryMap = new HashMap<Integer, Integer>();
            List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
            for (MachineBatteryModel mbm : machineBatterys) {
                machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
            }

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIdList);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            for (MachineStatus ms : machineStatus) {
                if (machineBorrowMap.containsKey(ms.getMachineId())) {
                    ms.setInUse(1);
                } else {
                    ms.setInUse(0);
                }

                Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
                ms.setBatteryModelId(batteryModelId);
                ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
            }
        }

        return machineStatus;
    }

    @Override
    public List<MachineStatusBorrow> getByUnuse(AccountUser accountUserToken, Integer accountId, Integer hours, Integer mapType, List<Integer> regionId, Integer start, Integer end) {
        List<MachineStatusBorrow> machineStatusBorrows;
        // 兼容自定义闲置区间
        if (start != null && end != null) {
            String startTime = DateUtil.formatDateTime(DateUtil.offsetDay(new Date(), -start));
            String endTime = DateUtil.formatDateTime(DateUtil.offsetDay(new Date(), -end));
            if (CollectionUtils.isEmpty(regionId)) {
                machineStatusBorrows = machineStatusService.getUnUseByStartEnd(accountId, startTime, endTime);
            } else {
                machineStatusBorrows = machineStatusService.getRegionByStartEnd(regionId, startTime, endTime);
            }
        } else {
            // 计算时间
            String lastBorrowTime = DateTimeUtil.getHoursAgo(hours);
            if (CollectionUtils.isEmpty(regionId)) {
                machineStatusBorrows = machineStatusService.getUnUseByAccountId(accountId, lastBorrowTime);
            } else {
                machineStatusBorrows = machineStatusService.getUnUseByRegionId(regionId, lastBorrowTime);
            }
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUserToken.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatusBorrows = machineStatusBorrows.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatusBorrows)) {
            return Collections.emptyList();
        }
        if (CollectionUtils.isNotEmpty(machineStatusBorrows)) {

            calibrateService.celibrateMachineStatusBorrow(machineStatusBorrows, mapType);

            /**挪车调度，区域*/
            List<String> userCodeMove = new LinkedList<>();
            try {
                userCodeMove = redisService.getList(RedisConstant.REDIS_BATCH_MOVE_AREA + accountId);
            } catch (SerializationException e) {
                redisService.del(RedisConstant.REDIS_BATCH_MOVE_AREA + accountId);
            }

            Set<String> machineNoInMove = userCodeMove.stream().map(dataService::getMachineNO)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toSet());


            /**批量调度，区域*/
            List<String> areaDispatchMachineCache = new LinkedList<>();
            try {
                areaDispatchMachineCache = redisService.getList(RedisConstant.REDIS_BATCH_DISPATCH_AREA + accountId);
            } catch (SerializationException e) {
                redisService.del(RedisConstant.REDIS_BATCH_DISPATCH_AREA + accountId);
            }
            Set<String> machineNoInDispatch = areaDispatchMachineCache.stream().map(dataService::getMachineNO)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toSet());

            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            for (MachineStatusBorrow msb : machineStatusBorrows) {
                msb.setStock(stockMachineIds.contains(msb.getMachineId()));
                msb.setDetention(detentionMachineIds.contains(msb.getMachineId()));

                if (machineNoInMove.contains(msb.getMachineNO())) {
                    msb.setMoveState(1);
                    continue;
                }
                if (machineNoInDispatch.contains(msb.getMachineNO())) {
                    msb.setMoveState(2);
                }
            }
        }

        /**获取电池编号*/
        List<BatteryMachine> batteryMachineList;
        if (CollectionUtils.isEmpty(regionId)) {
            batteryMachineList = batteryMachineService.getByAccountId(accountId);
        } else {
            batteryMachineList = batteryMachineService.getByRegionIds(regionId);
        }
        Map<Integer, String> batteryMachineMap = new HashMap<>();
        for (BatteryMachine batteryMachine : batteryMachineList) {
            batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
        }

        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatusBorrow ms : machineStatusBorrows) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
            ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
        }

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineStatusBorrows.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIds = machineStatusBorrows.stream().map(MachineStatusBorrow::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIds, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_XZCL);
            machineStatusBorrows = machineStatusBorrows.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }

        return machineStatusBorrows;
    }

    @Override
    public List<MachineStatusFault> getByFault(AccountUser accountUser, Integer accountId, Integer mapType, List<Integer> faultState, List<Integer> regionId) {
        List<MachineStatusFault> machineStatusFaults = new ArrayList<>();

        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses;
        if (CollUtil.isEmpty(regionId)) {
            machineStatuses = machineStatusService.getFaultByAccountId(accountId, faultState);
        } else {
            machineStatuses = machineStatusService.getFaultByRegionId(regionId, faultState);
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatuses)) {
            return Collections.emptyList();
        }
        /**获取电池编号*/
        List<BatteryMachine> batteryMachineList;
        if (CollUtil.isEmpty(regionId)) {
            batteryMachineList = batteryMachineService.getByAccountId(accountId);
        } else {
            batteryMachineList = batteryMachineService.getByRegionIds(regionId);
        }
        Map<Integer, String> batteryMachineMap = new HashMap<>();
        for (BatteryMachine batteryMachine : batteryMachineList) {
            batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
        }

        if (CollUtil.isNotEmpty(machineStatuses)) {
            /**校准*/
            calibrateService.celibrateMachineStatus(machineStatuses, mapType);

            /**查询故障*/
            Map<Integer, MachineFault> machineFaultMap = new HashMap<>();
            List<MachineFault> machineFaults;
            if (CollUtil.isEmpty(regionId)) {
                machineFaults = machineFaultService.getByAccountId(accountId);
            } else {
                machineFaults = machineFaultService.getByRegionId(regionId);
            }
            for (MachineFault mf : machineFaults) {
                machineFaultMap.put(mf.getMachineId(), mf);
            }

            for (MachineStatus ms : machineStatuses) {
                MachineStatusFault msf = new MachineStatusFault();

                msf.setMachineId(ms.getMachineId());
                msf.setMachineNO(ms.getMachineNO());
                msf.setLon(ms.getLon());
                msf.setLat(ms.getLat());
                msf.setLonC(ms.getLonC());
                msf.setLatC(ms.getLatC());
                msf.setPosDt(ms.getPosDt());
                msf.setBatDt(ms.getBatDt());
                msf.setSocPercent(ms.getSocPercent());
                msf.setSurplusMileage(ms.getSurplusMileage());
                msf.setState(ms.getState());
                msf.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                /**故障来源*/
                MachineFault mf = machineFaultMap.get(msf.getMachineId());
                if (mf != null) {
                    msf.setFaultFrom(mf.getFrom());
                    /**故障类型*/
                    msf.setFaultType(mf.getFaults());
                    machineStatusFaults.add(msf);
                }
            }
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusFaults)) {
            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusFault ms : machineStatusFaults) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setMachineType(machine.getMachineType());
                }
            }
        }

        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatusFault ms : machineStatusFaults) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
        }

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineStatusFaults.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            /**返回数据*/
            List<MachineStatusFault> faults = new ArrayList<>();
            List<MachineStatusFault> ywFault = machineStatusFaults.stream().filter(machineStatusFault -> machineStatusFault.getFaultFrom() == 0).collect(
                    Collectors.toList());
            List<MachineStatusFault> yhFault = machineStatusFaults.stream().filter(machineStatusFault -> machineStatusFault.getFaultFrom() == 1).collect(
                    Collectors.toList());
            /**运维异常校验*/
            List<Integer> ywMachineIds = ywFault.stream().map(MachineStatusFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(ywMachineIds)) {
                List<Integer> delIds = devicePriorityService.checkPriority(ywMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YWGZ);
                ywFault = ywFault.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**用户异常校验*/
            List<Integer> yhMachineIds = yhFault.stream().map(MachineStatusFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(yhMachineIds)) {
                List<Integer> yhdelIds = devicePriorityService.checkPriority(yhMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YHGZ);
                yhFault = yhFault.stream().filter(machineStatus -> !yhdelIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**求并集*/
            faults.addAll(ywFault);
            faults.addAll(yhFault);
            machineStatusFaults = faults;
        }
        return machineStatusFaults;
    }

    @Override
    public List<MachineStatusAbnormal> getByAbnormal(AccountUser accountUser, Integer accountId, Integer abnormalType, Integer mapType, List<Integer> regionId, Integer hours) {
        List<MachineStatusAbnormal> machineStatusAbnormals = new ArrayList<>();

        /**计算时间*/
        String addTime = null;
        if (hours != null) {
            addTime = DateTimeUtil.getHoursAgo(hours);
        }

        /**查询异常车辆*/
        List<MachineAbnormal> machineAbnormals;

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);

        if (accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            if (CollUtil.isEmpty(regionId)) {
                machineAbnormals = machineAbnormalService.groupMachineIdAndType(accountId, abnormalType, null);
            } else {
                machineAbnormals = machineAbnormalService.groupMachineIdAndRegionId(regionId, abnormalType, null);
            }
        } else {
            if (CollUtil.isEmpty(regionId)) {
                machineAbnormals = machineAbnormalService.groupByMachineIdAndType(accountId, abnormalType, addTime);
            } else {
                machineAbnormals = machineAbnormalService.groupByMachineIdAndRegionId(regionId, abnormalType, addTime);
            }
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineAbnormals = machineAbnormals.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineAbnormals)) {
            return Collections.emptyList();
        }
        if (CollUtil.isNotEmpty(machineAbnormals)) {

            List<Integer> machineIds = new ArrayList<Integer>();
            Map<Integer, List<Integer>> abnormalMap = new HashMap<Integer, List<Integer>>();
            for (MachineAbnormal ma : machineAbnormals) {
                if (abnormalMap.containsKey(ma.getMachineId())) {
                    abnormalMap.get(ma.getMachineId()).add(ma.getAbnormalType());
                } else {
                    machineIds.add(ma.getMachineId());
                    List<Integer> a = new LinkedList<>();
                    a.add(ma.getAbnormalType());
                    abnormalMap.put(ma.getMachineId(), a);
                }
            }

            /**查询所有设备状态*/
            List<MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            if (CollUtil.isNotEmpty(machineStatuses)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatuses, mapType);
                for (MachineStatus ms : machineStatuses) {
                    if (abnormalMap.get(ms.getMachineId()) != null) {
                        for (Integer type : abnormalMap.get(ms.getMachineId())) {
                            MachineStatusAbnormal msa = new MachineStatusAbnormal();
                            msa.setMachineId(ms.getMachineId());
                            msa.setMachineNO(ms.getMachineNO());
                            msa.setLon(ms.getLon());
                            msa.setLat(ms.getLat());
                            msa.setLonC(ms.getLonC());
                            msa.setLatC(ms.getLatC());
                            msa.setPosDt(ms.getPosDt());
                            msa.setBatDt(ms.getBatDt());
                            msa.setSocPercent(ms.getSocPercent());
                            msa.setSurplusMileage(ms.getSurplusMileage());
                            msa.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                            msa.setState(ms.getState());
                            /**异常类型*/
                            msa.setAbnormalType(type);
                            machineStatusAbnormals.add(msa);
                        }
                    }
                }
            }
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusAbnormals)) {
            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<Integer, Machine>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusAbnormal ms : machineStatusAbnormals) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setMachineType(machine.getMachineType());
                }
            }
        }

        /**车辆功能优先级逻辑判断*/
        if (!machineStatusAbnormals.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIds = machineStatusAbnormals.stream().map(MachineStatusAbnormal::getMachineId).collect(Collectors.toList());
            if (abnormalType == null) {
                machineStatusAbnormals = getAbnormalTypeDel(machineStatusAbnormals, accountId, regionId);
            } else {
                List<Integer> delIds = devicePriorityService.checkPriority(machineIds, accountId,
                        transfanType(abnormalType));
                machineStatusAbnormals = machineStatusAbnormals.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }
        }
        return machineStatusAbnormals;
    }

    @Override
    public List<MachineStatusAbnormal> getByAbnormalList(Integer accountId, List<Integer> abnormalType, Integer mapType, List<Integer> regionId) {
        List<MachineStatusAbnormal> machineStatusAbnormals = new ArrayList<>();

        /**查询异常车辆*/
        List<MachineAbnormal> machineAbnormals;
        if (CollUtil.isEmpty(regionId)) {
            machineAbnormals = machineAbnormalService.groupByMachineIdAndListType(accountId, abnormalType);
        } else {
            machineAbnormals = machineAbnormalService.groupByMachineIdRegionIdAndType2(regionId, abnormalType);
        }
        if (CollUtil.isNotEmpty(machineAbnormals)) {
            List<Integer> machineIds = new ArrayList<>();
            Map<Integer, Integer> abnormalMap = new HashMap<>();
            for (MachineAbnormal ma : machineAbnormals) {
                machineIds.add(ma.getMachineId());
                abnormalMap.put(ma.getMachineId(), ma.getAbnormalType());
            }

            /**查询所有设备状态*/
            List<MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            if (CollUtil.isNotEmpty(machineStatuses)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatuses, mapType);

                for (MachineStatus ms : machineStatuses) {
                    MachineStatusAbnormal msa = new MachineStatusAbnormal();

                    msa.setMachineId(ms.getMachineId());
                    msa.setMachineNO(ms.getMachineNO());
                    msa.setLon(ms.getLon());
                    msa.setLat(ms.getLat());
                    msa.setLonC(ms.getLonC());
                    msa.setLatC(ms.getLatC());
                    msa.setPosDt(ms.getPosDt());
                    msa.setBatDt(ms.getBatDt());
                    msa.setSocPercent(ms.getSocPercent());
                    msa.setSurplusMileage(ms.getSurplusMileage());
                    msa.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                    msa.setState(ms.getState());
                    /**异常类型*/
                    Integer abnormalTypeCache = abnormalMap.get(ms.getMachineId());
                    if (abnormalTypeCache != null) {
                        msa.setAbnormalType(abnormalTypeCache);
                    }

                    machineStatusAbnormals.add(msa);
                }
            }
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusAbnormals)) {
            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusAbnormal ms : machineStatusAbnormals) {
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                }
            }
        }

        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatusAbnormal ms : machineStatusAbnormals) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
        }

        return machineStatusAbnormals;
    }

    @Override
    public List<MachineStatus> getByOccupy(AccountUser accountUserToken, Integer accountId, Integer mapType, List<Integer> regionId) {
        List<MachineStatus> machineStatuses = new ArrayList<>();

        /**查询运维占用中车辆*/
        List<MachineOccupy> machineOccupys;
        if (CollUtil.isEmpty(regionId)) {
            machineOccupys = machineOccupyService.getByAccountId(accountId);
        } else {
            machineOccupys = machineOccupyService.getByRegionId(regionId);
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUserToken.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineOccupys = machineOccupys.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineOccupys)) {
            return Collections.emptyList();
        }
        if (CollUtil.isNotEmpty(machineOccupys)) {

            Map<Integer, Integer> occupyId = new HashMap<>();

            List<Integer> machineIds = new ArrayList<>();
            for (MachineOccupy mo : machineOccupys) {
                machineIds.add(mo.getMachineId());
                occupyId.put(mo.getMachineId(), mo.getAccountUserId());
            }
            machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            List<Machine> machines = machineService.getByMachineIds(machineIds);
            Map<Integer, Machine> machineMap = new HashMap<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            /**运维人员*/
            List<AccountUser> accountUsers = accountUserService.getByIds(new ArrayList<>(occupyId.values()));
            Map<Integer, String> accountUserMap = new HashMap<>();
            for (AccountUser accountUser : accountUsers) {
                accountUserMap.put(accountUser.getAccountUserId(), accountUser.getName());
            }

            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            for (MachineStatus ms : machineStatuses) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                }
                ms.setUserId(occupyId.get(ms.getMachineId()));
                ms.setUserName(accountUserMap.get(occupyId.get(ms.getMachineId())));

            }

            /** 校准 */
            if (CollUtil.isNotEmpty(machineStatuses)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatuses, mapType);
            }
        }

        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatus ms : machineStatuses) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
        }

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineStatuses.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIds = machineStatuses.stream().map(MachineStatus::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIds, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_YWZY);

            machineStatuses = machineStatuses.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }
        return machineStatuses;
    }

    @Override
    public List<MachineStatus> getByUseIng(AccountUser accountUserToken, Integer accountId, Integer mapType, List<Integer> regionId) {
        List<MachineStatus> machineStatuses = new ArrayList<>();

        /**查询骑行中车辆*/
        List<Machine> machineOccupys;
        if (CollUtil.isEmpty(regionId)) {
            machineOccupys = machineService.getUseingByAccountId(accountId);
        } else {
            machineOccupys = machineService.getUseingByRegionId(regionId);
        }
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUserToken.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineOccupys = machineOccupys.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineOccupys)) {
            return Collections.emptyList();
        }
        if (CollUtil.isNotEmpty(machineOccupys)) {

            Map<Integer, Integer> occupyId = new HashMap<>();

            List<Integer> machineIds = new ArrayList<>();
            for (Machine mo : machineOccupys) {
                machineIds.add(mo.getMachineId());
                occupyId.put(mo.getMachineId(), mo.getLastUserId());
            }
            machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            List<Machine> machines = machineService.getByMachineIds(machineIds);
            Map<Integer, Machine> machineMap = new HashMap<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            /**用户人员*/
            List<User> accountUsers = userService.getUserIds(new ArrayList<>(occupyId.values()));
            Map<Integer, User> accountUserMap = new HashMap<>();
            for (User accountUser : accountUsers) {
                accountUserMap.put(accountUser.getUserId(), accountUser);
            }

            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            for (MachineStatus ms : machineStatuses) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));

                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                }
                ms.setUserId(occupyId.get(ms.getMachineId()));
                ms.setUserName(accountUserMap.get(occupyId.get(ms.getMachineId())).getName());
                ms.setPhone(accountUserMap.get(occupyId.get(ms.getMachineId())).getPhone());
            }

            /** 校准 */
            if (CollUtil.isNotEmpty(machineStatuses)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatuses, mapType);
            }
        }

        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatus ms : machineStatuses) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
        }

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineStatuses.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIds = machineStatuses.stream().map(MachineStatus::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIds, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_QXZ);

            machineStatuses = machineStatuses.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(machineStatuses)) {
            Map<Integer, String> longOrderTime = getLongOrderTime(machineStatuses.stream().map(MachineStatus::getMachineId).collect(Collectors.toList()), accountId);
            if (CollectionUtil.isNotEmpty(longOrderTime)) {
                for (MachineStatus machineStatus : machineStatuses) {
                    machineStatus.setLongOrderHour(longOrderTime.getOrDefault(machineStatus.getMachineId(), ""));
                }
            }
        }

        return machineStatuses;
    }

    @Override
    public List<MachineStatus> getAbnormalReturn(AccountUser accountUser, Integer accountId, Integer mapType, List<Integer> regionId, Integer type) {
        List<MachineStatus> machineStatuses = new ArrayList<>();

        /**查询还车失败车辆*/
        List<VerticalParkLog> verticalParkLog = new LinkedList<>();
        if (type == 1) {
            if (CollUtil.isEmpty(regionId)) {
                verticalParkLog = verticalParkLogService.getMachineAccountId(accountId);
            } else {
                verticalParkLog = verticalParkLogService.getMachineRegionId(regionId);
            }
        }

        if (verticalParkLog != null && !verticalParkLog.isEmpty()) {

            Map<String, VerticalParkLog> map = new HashMap<>();
            for (VerticalParkLog verticalParkLog1 : verticalParkLog) {
                map.put(verticalParkLog1.getMachineNO(), verticalParkLog1);
            }

            List<String> machineNOS = verticalParkLog.stream().map(VerticalParkLog::getMachineNO).collect(Collectors.toList());

            List<Machine> machines = machineService.getByMachineNOs(machineNOS);

            List<Integer> machineIds = machines.stream().map(Machine::getMachineId).collect(Collectors.toList());

            machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            Map<Integer, Machine> machineMap = new HashMap<>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            /**获取电池编号*/
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }


            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            for (MachineStatus ms : machineStatuses) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));

                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                }
                VerticalParkLog verticalParkLog1 = map.get(ms.getMachineNO());
                if (verticalParkLog1 != null) {
                    ms.setMachineAngle(verticalParkLog1.getMachineAngle());
                    ms.setParkAngle(verticalParkLog1.getParkAngle());
                    ms.setDifference(verticalParkLog1.getDifference());
                }
            }

            /** 校准 */
            if (CollUtil.isNotEmpty(machineStatuses)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatuses, mapType);
            }
        }


        /**查询电池方案*/
        Map<Integer, Integer> machineBatteryMap = new HashMap<>();
        List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
        for (MachineBatteryModel mbm : machineBatterys) {
            machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
        }
        for (MachineStatus ms : machineStatuses) {
            Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
            ms.setBatteryModelId(batteryModelId);
        }
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        return machineStatuses;
    }

    @Override
    public List<MachineStatus> getByStream(AccountUser accountUserToken, Integer accountId, List<Integer> regionId, Integer mapType) {

        List<MachineStatus> machineStatus = new LinkedList<>();

        if (CollUtil.isEmpty(regionId)) {
            List<GeoreGion> geoRegions = georeGionService.getByAccountId(accountId);
            regionId = geoRegions.stream().map(GeoreGion::getRegionId).collect(Collectors.toList());
        }
        if (CollUtil.isNotEmpty(regionId)) {
            machineStatus = machineStatusService.getStream(regionId);
            List<Integer> superviseMachine = selectSuperviseMachine(accountUserToken.getAccountUserType(), accountId);
            if (CollUtil.isNotEmpty(superviseMachine)) {
                machineStatus = machineStatus.stream()
                        .filter(x -> superviseMachine.contains(x.getMachineId()))
                        .collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(machineStatus)) {
                return Collections.emptyList();
            }

            /**获取电池编号*/
            List<Integer> machineIds = machineStatus.stream().map(MachineStatus::getMachineId).collect(Collectors.toList());
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIds);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            /** 校准 */
            if (CollUtil.isNotEmpty(machineStatus)) {
                /**校准*/
                calibrateService.celibrateMachineStatus(machineStatus, mapType);

                /** 查询当前在使用车辆 */
                Map<Integer, MachineBorrow> machineBorrowMap = new HashMap<>();
                List<MachineBorrow> machineBorrows;
                machineBorrows = machineBorrowService.getByRegionId(regionId);
                for (MachineBorrow mb : machineBorrows) {
                    machineBorrowMap.put(mb.getMachineId(), mb);
                }

                /**查询电池方案*/
                Map<Integer, Integer> machineBatteryMap = new HashMap<>();
                List<MachineBatteryModel> machineBatterys = batteryModelService.getMachineBatteryModel(accountId);
                for (MachineBatteryModel mbm : machineBatterys) {
                    machineBatteryMap.put(mbm.getMachineId(), mbm.getBatteryModelId());
                }

                // 回收车辆
                List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                        .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

                // 扣押车辆
                List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                        .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

                for (MachineStatus ms : machineStatus) {
                    ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                    ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));

                    if (machineBorrowMap.containsKey(ms.getMachineId())) {
                        ms.setInUse(1);
                    } else {
                        ms.setInUse(0);
                    }

                    Integer batteryModelId = machineBatteryMap.get(ms.getMachineId());
                    ms.setBatteryModelId(batteryModelId);
                    ms.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                }
            }
        }
        return machineStatus;

    }

    @Override
    public List<MachineStatusAbnormal> getAbnormalType(Integer accountId, List<Integer> abnormalType) {
        List<MachineStatusAbnormal> machineStatusAbnormals = new ArrayList<>();

        /**查询异常车辆*/
        List<MachineAbnormal> machineAbnormals = machineAbnormalService.groupByMachineIdAndListType(accountId, abnormalType);

        if (CollUtil.isNotEmpty(machineAbnormals)) {
            List<Integer> machineIds = new ArrayList<>();
            Map<Integer, Integer> abnormalMap = new HashMap<>();
            for (MachineAbnormal ma : machineAbnormals) {
                machineIds.add(ma.getMachineId());
                abnormalMap.put(ma.getMachineId(), ma.getAbnormalType());
            }

            /**查询所有设备状态*/
            List<MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);

            /**获取电池编号*/
            List<Integer> machineIdList = machineStatuses.stream().map(MachineStatus::getMachineId).collect(Collectors.toList());
            List<BatteryMachine> batteryMachineList = batteryMachineService.getByMachineIds(machineIdList);
            Map<Integer, String> batteryMachineMap = new HashMap<>();
            for (BatteryMachine batteryMachine : batteryMachineList) {
                batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
            }

            if (CollUtil.isNotEmpty(machineStatuses)) {
                for (MachineStatus ms : machineStatuses) {
                    MachineStatusAbnormal msa = new MachineStatusAbnormal();

                    msa.setMachineId(ms.getMachineId());
                    msa.setMachineNO(ms.getMachineNO());
                    msa.setLon(ms.getLon());
                    msa.setLat(ms.getLat());
                    msa.setPosDt(ms.getPosDt());
                    msa.setBatDt(ms.getBatDt());
                    msa.setSocPercent(ms.getSocPercent());
                    msa.setSurplusMileage(ms.getSurplusMileage());
                    msa.setState(ms.getState());
                    /**异常类型*/
                    Integer abnormalTypeCache = abnormalMap.get(ms.getMachineId());
                    if (abnormalTypeCache != null) {
                        msa.setAbnormalType(abnormalTypeCache);
                    }
                    msa.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
                    machineStatusAbnormals.add(msa);
                }
            }
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusAbnormals)) {
            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<Integer, Machine>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusAbnormal ms : machineStatusAbnormals) {
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                }
            }
        }
        return machineStatusAbnormals;
    }

    @Override
    public List<MachineStatusBorrow> getNoIncome(AccountUser accountUserToken, Integer accountId, Integer mapType, List<Integer> regionId, Integer count) {
        List<MachineStatusBorrow> machineStatusBorrows = new ArrayList<>();

        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses;
        if (CollectionUtils.isEmpty(regionId)) {
            machineStatuses = machineNoIncomeService.getByAccountIdAndCount(accountId, count);
        } else {
            machineStatuses = machineNoIncomeService.getByRegionIdAndCount(regionId, count);
        }
        List<Integer> superviseMachine = selectSuperviseMachine(accountUserToken.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatuses)) {
            return Collections.emptyList();
        }

        /**查询正在借用设备*/
        Map<Integer, MachineBorrow> machineBorrowMap = new HashMap<>();
        List<MachineBorrow> machineBorrows;
        if (CollectionUtils.isEmpty(regionId)) {
            machineBorrows = machineBorrowService.getByAccountId(accountId);
        } else {
            machineBorrows = machineBorrowService.getByRegionId(regionId);
        }
        for (MachineBorrow mb : machineBorrows) {
            machineBorrowMap.put(mb.getMachineId(), mb);
        }

        /**查询所有异常设备*/
        Map<Integer, Integer> machineAbnormalMap = new HashMap<>();
        List<MachineAbnormal> machineAbnormals;
        if (CollectionUtils.isEmpty(regionId)) {
            machineAbnormals = machineAbnormalService.groupByMachineIdAndType(accountId, null, null);
        } else {
            machineAbnormals = machineAbnormalService.groupByMachineIdAndRegionId(regionId, null, null);
        }
        for (MachineAbnormal ma : machineAbnormals) {
            machineAbnormalMap.put(ma.getMachineId(), ma.getMachineId());
        }

        /**查询所有故障设备*/
        Map<Integer, Integer> machineFaultMap = new HashMap<>();
        List<MachineFault> machineFaults;
        if (CollectionUtils.isEmpty(regionId)) {
            machineFaults = machineFaultService.getByAccountId(accountId);
        } else {
            machineFaults = machineFaultService.getByRegionId(regionId);
        }
       /* //疑似故障
        Map<Integer, MachineFault> suspectedFaultMap = machineFaults.stream().filter(machineFault -> {
            return Objects.equals(machineFault.getFrom(), 4);
        }).collect(Collectors.toList()).stream().collect(Collectors.toMap(MachineFault::getMachineId, Function.identity()));

        machineFaults = machineFaults.stream().filter(machineFault -> {
            //过滤掉疑似故障
            return !Objects.equals(machineFault.getFrom(),4);
        }).collect(Collectors.toList());*/

        for (MachineFault mf : machineFaults) {
            machineFaultMap.put(mf.getMachineId(), mf.getMachineId());
        }

        /**获取电池编号*/
        List<BatteryMachine> batteryMachineList;
        if (CollectionUtils.isEmpty(regionId)) {
            batteryMachineList = batteryMachineService.getByAccountId(accountId);
        } else {
            batteryMachineList = batteryMachineService.getByRegionIds(regionId);
        }
        Map<Integer, String> batteryMachineMap = new HashMap<>();
        for (BatteryMachine batteryMachine : batteryMachineList) {
            batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
        }

        for (MachineStatus ms : machineStatuses) {
            MachineStatusBorrow msb = new MachineStatusBorrow();

            /**是否使用中*/
            MachineBorrow mb = machineBorrowMap.get(ms.getMachineId());
            if (mb == null) {
                msb.setIsUse(false);
            } else {
                msb.setIsUse(true);
            }


            /**是否故障*/
            Integer isAbnormal = machineAbnormalMap.get(ms.getMachineId());
            if (isAbnormal != null) {
                msb.setIsAbnormal(true);
            } else {
                msb.setIsAbnormal(false);
            }

            /**是否异常*/
            Integer isFault = machineFaultMap.get(ms.getMachineId());
            if (isFault != null) {
                msb.setIsFault(true);
            } else {
                msb.setIsFault(false);
            }

            /**疑似故障*/
            /*MachineFault machineFault = suspectedFaultMap.get(ms.getMachineId());
            msb.setSuspectedFault(Objects.nonNull(machineFault));*/

            msb.setMachineId(ms.getMachineId());
            msb.setMachineNO(ms.getMachineNO());
            msb.setLon(ms.getLon());
            msb.setLat(ms.getLat());
            msb.setPosDt(ms.getPosDt());
            msb.setBatDt(ms.getBatDt());
            msb.setSocPercent(ms.getSocPercent());
            msb.setSurplusMileage(ms.getSurplusMileage());
            msb.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
            msb.setNoIncome(ms.getNoIncome());
            machineStatusBorrows.add(msb);
        }

        /**校准*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            calibrateService.celibrateMachineStatusBorrow(machineStatusBorrows, mapType);
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            // 回收车辆
            List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                    .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

            // 扣押车辆
            List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                    .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<Integer, Machine>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusBorrow ms : machineStatusBorrows) {
                ms.setStock(stockMachineIds.contains(ms.getMachineId()));
                ms.setDetention(detentionMachineIds.contains(ms.getMachineId()));
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setMachineType(machine.getMachineType());
                    ms.setState(machine.getState());
                }
            }
        }

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineStatusBorrows.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIds = machineStatusBorrows.stream().map(MachineStatusBorrow::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIds, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_WYL);
            machineStatusBorrows = machineStatusBorrows.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }
        return machineStatusBorrows;
    }

    @Override
    public List<MachineStatus> getByDetention(Integer accountId, Integer mapType,
                                              List<Integer> regionId) {

        List<DetentionMachineBound> detentionMachineBounds = detentionMachineBoundService.getListByAccount(accountId);

        if (detentionMachineBounds.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> machineIds = detentionMachineBounds.stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());
        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);
        calibrateService.celibrateMachineStatus(machineStatuses, mapType);
        Map<Integer, Machine> machineMap = machineService.getByMachineIds(machineIds).stream().collect(Collectors.toMap(Machine::getMachineId, p -> p));

        // 回收车辆
        List<Integer> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId)
                .stream().map(StockMachine::getMachineId).collect(Collectors.toList());

        machineStatuses.forEach(m -> {
            m.setStock(stockMachineIds.contains(m.getMachineId()));
            if (machineMap.get(m.getMachineId()) != null) {
                m.setUserCode(machineMap.get(m.getMachineId()).getUserCode());
                m.setMachineNO(machineMap.get(m.getMachineId()).getMachineNO());
            }
        });

        /**车辆功能优先级逻辑判断*/
        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        if (!machineStatuses.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIdList = machineStatuses.stream().map(MachineStatus::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIdList, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_KYZT);
            machineStatuses = machineStatuses.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }
        return machineStatuses;
    }

    @Override
    public List<MachineStatus> getByStock(Integer accountId, Integer mapType, List<Integer> regionId) {

        /**回收车辆*/
        List<StockMachine> stockMachineIds = stockMachineService.getByAccountId(accountId, regionId);
        if (CollUtil.isEmpty(stockMachineIds)) {
            return Collections.emptyList();
        }

        List<Integer> machineIds = stockMachineIds.stream().map(StockMachine::getMachineId).collect(Collectors.toList());

        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses = machineStatusService.getByMachineIdBatch(machineIds);
        calibrateService.celibrateMachineStatus(machineStatuses, mapType);
        Map<Integer, Machine> machineMap = machineService.getByMachineIds(machineIds).stream().collect(Collectors.toMap(Machine::getMachineId, p -> p));

        // 扣押车辆
        List<Integer> detentionMachineIds = detentionMachineBoundService.getListByAccount(accountId)
                .stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

        machineStatuses.forEach(m -> {
            m.setDetention(detentionMachineIds.contains(m.getMachineId()));
            if (machineMap.get(m.getMachineId()) != null) {
                m.setUserCode(machineMap.get(m.getMachineId()).getUserCode());
                m.setMachineNO(machineMap.get(m.getMachineId()).getMachineNO());
            }
        });

        /**车辆功能优先级逻辑判断*/
        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        if (!machineStatuses.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> machineIdList = machineStatuses.stream().map(MachineStatus::getMachineId).collect(
                    Collectors.toList());
            List<Integer> delIds = devicePriorityService.checkPriority(machineIdList, accountId,
                    DevicePriorityConstant.DEVICEPRIORITY_RKZ);
            machineStatuses = machineStatuses.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
        }

        return machineStatuses;
    }

    @Override
    public List<MachineStatusAbnormal> getAbnormalTypeDel(List<MachineStatusAbnormal> machineStatusAbnormals, Integer accountId, List<Integer> regionId) {
        /**查询所有异常设备*/
        List<MachineStatusAbnormal> machineAbnormalMap = new LinkedList<>();

        /**异常类型：车辆id*/
        Map<Integer, List<Integer>> machineAbnormalTypeMap = new HashMap<Integer, List<Integer>>();

        Map<Integer, List<MachineStatusAbnormal>> integerListMap = new HashMap<>();

        for (MachineStatusAbnormal machineStatusAbnormal : machineStatusAbnormals) {
            if (integerListMap.containsKey(machineStatusAbnormal.getAbnormalType())) {
                integerListMap.get(machineStatusAbnormal.getAbnormalType()).add(machineStatusAbnormal);
                machineAbnormalTypeMap.get(machineStatusAbnormal.getAbnormalType()).add(machineStatusAbnormal.getMachineId());
            } else {
                List<MachineStatusAbnormal> machineStatusAbnormalsList = new LinkedList<>();
                machineStatusAbnormalsList.add(machineStatusAbnormal);
                integerListMap.put(machineStatusAbnormal.getAbnormalType(), machineStatusAbnormalsList);

                List<Integer> machineId = new LinkedList<>();
                machineId.add(machineStatusAbnormal.getMachineId());
                machineAbnormalTypeMap.put(machineStatusAbnormal.getAbnormalType(), machineId);
            }
        }

        List<Integer> existMachineId = new LinkedList<>();

        /**判断优先级*/
        for (Integer key : machineAbnormalTypeMap.keySet()) {
            List<Integer> machineIds = machineAbnormalTypeMap.get(key);
            /**克隆*/
            List<Integer> temp = new LinkedList<>();
            BeanUtils.copyProperties(machineIds, temp);
            temp.addAll(machineIds);
            List<Integer> delIds = devicePriorityService.checkPriority(temp, accountId, transfanType(key));

            List<MachineStatusAbnormal> machineStatusAbnormalsExit = integerListMap.get(key).stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(existMachineId)) {
                machineStatusAbnormalsExit = machineStatusAbnormalsExit.stream().filter(machineStatus -> !existMachineId.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
                existMachineId.addAll(machineStatusAbnormalsExit.stream().map(MachineStatusAbnormal::getMachineId).collect(Collectors.toList()));
            }

            machineAbnormalMap.addAll(machineStatusAbnormalsExit);
        }

        return machineAbnormalMap;
    }

    @Override
    public List<MachineAbnormal> getAbnormalTypeDelMachineAbnormal(List<MachineAbnormal> machineStatusAbnormals, Integer accountId, List<Integer> regionId) {
        /**查询所有异常设备*/
        List<MachineAbnormal> machineAbnormalMap = new LinkedList<>();

        /**异常类型：车辆id*/
        Map<Integer, List<Integer>> machineAbnormalTypeMap = new HashMap<Integer, List<Integer>>();

        Map<Integer, List<MachineAbnormal>> integerListMap = new HashMap<>();

        for (MachineAbnormal machineStatusAbnormal : machineStatusAbnormals) {
            if (integerListMap.containsKey(machineStatusAbnormal.getAbnormalType())) {
                integerListMap.get(machineStatusAbnormal.getAbnormalType()).add(machineStatusAbnormal);
                machineAbnormalTypeMap.get(machineStatusAbnormal.getAbnormalType()).add(machineStatusAbnormal.getMachineId());
            } else {
                List<MachineAbnormal> machineStatusAbnormalsList = new LinkedList<>();
                machineStatusAbnormalsList.add(machineStatusAbnormal);
                integerListMap.put(machineStatusAbnormal.getAbnormalType(), machineStatusAbnormalsList);

                List<Integer> machineId = new LinkedList<>();
                machineId.add(machineStatusAbnormal.getMachineId());
                machineAbnormalTypeMap.put(machineStatusAbnormal.getAbnormalType(), machineId);
            }
        }

        List<Integer> existMachineId = new LinkedList<>();
        /**判断优先级*/
        for (Integer key : machineAbnormalTypeMap.keySet()) {
            List<Integer> machineIds = machineAbnormalTypeMap.get(key);
            /**克隆*/
            List<Integer> temp = new LinkedList<>();
            BeanUtils.copyProperties(machineIds, temp);
            temp.addAll(machineIds);
            List<Integer> delIds = devicePriorityService.checkPriority(temp, accountId, transfanType(key));

            List<MachineAbnormal> machineStatusAbnormalsExit = integerListMap.get(key).stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                    Collectors.toList());

            if (CollUtil.isNotEmpty(existMachineId)) {
                machineStatusAbnormalsExit = machineStatusAbnormalsExit.stream().filter(machineStatus -> !existMachineId.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
                existMachineId.addAll(machineStatusAbnormalsExit.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toList()));
            }

            machineAbnormalMap.addAll(machineStatusAbnormalsExit);
        }
        return machineAbnormalMap;
    }

    /**
     * 异常类型转换
     *
     * @param abnormalType
     * @return
     */
    @Override
    public Integer transfanType(Integer abnormalType) {
        if (abnormalType == null) {
            return null;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_CCQY)) {
            return DevicePriorityConstant.DEVICEPRIORITY_CQ;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_ZW)) {
            return DevicePriorityConstant.DEVICEPRIORITY_ZW;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_WXH)) {
            return DevicePriorityConstant.DEVICEPRIORITY_WXH;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_DCYC)) {
            return DevicePriorityConstant.DEVICEPRIORITY_DCYC;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_JTYC)) {
            return DevicePriorityConstant.DEVICEPRIORITY_JTQ;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_DCS)) {
            return DevicePriorityConstant.DEVICEPRIORITY_DCWS;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_SXT)) {
            return DevicePriorityConstant.DEVICEPRIORITY_SXYC;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL__HELMET)) {
            return DevicePriorityConstant.DEVICEPRIORITY_TKYC;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL__HELMET_LOSE)) {
            return DevicePriorityConstant.DEVICEPRIORITY_TKDS;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_IMPOUND)) {
            return DevicePriorityConstant.DEVICEPRIORITY_KYZT;
        } else if (abnormalType.equals(MachineAbnormalConstant.MACHINE_ABNORMAL_STORAGE)) {
            return DevicePriorityConstant.DEVICEPRIORITY_RKZ;
        }
        return DevicePriorityConstant.DEVICEPRIORITY_TKDS;
    }

    @Override
    public void pushPost(String userCodeS, Double lon, Double lat, Double lonPeople, Double latPeople, Integer mapType) {
        /**查询设备信息*/
        String[] split = userCodeS.split(",");
        List<String> userCodes = Stream.of(split).collect(Collectors.toList());
        List<Machine> machines = machineService.getByUserCodes(userCodes);

        Point point = calibrateService.commonCalibrate(new Point(lon, lat), mapType, SysConstant.ORIGINAL);
        Point pointPerPle = calibrateService.commonCalibrate(new Point(lonPeople, latPeople), mapType, SysConstant.ORIGINAL);

        double distance = GeoUtil.getDistance(point, pointPerPle);
        LogUtil.info("距离：" + distance);

        Integer accountId = machines.stream().findAny().orElse(new Machine()).getAccountId();
        int distanceConfig = 100;
        if (accountId != null) {
            AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.batchMoveAndDispatchDistance);
            if (accountConfigExt != null) {
                distanceConfig = Integer.parseInt(accountConfigExt.getParamValue());
            }
        }

        if (distance > distanceConfig) {
            throw new BaseException(MessageUtil.get("point.people.is.long", distanceConfig));
        }

        doPushPos(point.getX(), point.getY(), machines);
    }

    /**
     * 更新多车辆多经纬度
     * <ul>
     *     <li><a href="https://doc.weixin.qq.com/doc/w3_AVsAUwYrAAc5MFvVcZ6T02877xum1?scode=ACsAvwcxAA48kzY5QYAVsAUwYrAAc&version=4.1.20.6024&platform=win">需求</a></li>
     *     <li>挪车、调度时，避免车辆在同一个经纬度，导致地图看不出来有多辆车问题</li>
     * </ul>
     *
     * @param machines 更新的车辆
     */
    private void doPushPos(Double lon, Double lat, List<Machine> machines) {

        // 获得站点附近 2 米，经纬度
        List<Point> randomPoint = RandomPointUtil.getRandomPoint(lon, lat, 2.0, machines.size());

        List<MachineStatusPos> machineStatusPoses = new ArrayList<>(machines.size());

        for (int i = 0; i < machines.size(); i++) {
            Machine machine = machines.get(i);

            Point point = randomPoint.get(i);

            MachineStatusPos machineStatusPos = getMachineStatusPosAndSendToQueue(machine, point);

            machineStatusPoses.add(machineStatusPos);
        }

        if (CollUtil.isNotEmpty(machineStatusPoses)) {
            // 批量更新经纬度
            machineStatusService.updateStatusPosBatch(machineStatusPoses);
        }
    }

    /**
     * 获得车辆最后状态位置并发送至 MQ
     *
     * @param machine 车辆
     * @param point   位置
     * @return 车辆最后状态位置
     */
    private MachineStatusPos getMachineStatusPosAndSendToQueue(Machine machine, Point point) {
        MachineStatus machineStatus = dataService.getMachineStatus(machine.getMachineId());
        if (machineStatus == null) {
            machineStatusService.insert(machine.getMachineId(), point, MachineStatusConstant.MACHINE_STATUS_SD);
        }

        MachineStatusPos machineStatusPos = new MachineStatusPos();
        machineStatusPos.setMachineId(machine.getMachineId());
        machineStatusPos.setMachineNO(machine.getMachineNO());
        machineStatusPos.setDt(System.currentTimeMillis());
        machineStatusPos.setPointType(-1);
        machineStatusPos.setLon(point.getX());
        machineStatusPos.setLat(point.getY());
        machineStatusPos.setCarStatus(machineStatus == null ? 0 : machineStatus.getTerStatus());

        TerControlMsg<MachineStatusPos> terControlMsg = new TerControlMsg<>();
        terControlMsg.setFeedback("tbit_uqbike_ter_position");
        terControlMsg.setMsgId(GatewayProtocol.MQ_MSG_ID_MACHINE_STATUS_POS);
        terControlMsg.setData(machineStatusPos);
        /**发送到MQ*/
        mqProducer.sendDataToQueue("tbit_uqbike_ter_position", JSON.toJSONString(terControlMsg));
        return machineStatusPos;
    }


    @Override
    public List<MachineStatusBorrow> getByTag(AccountUser accountUser, Integer accountId, Integer mapType, List<Integer> regionId, List<Integer> tagIds) {
        List<MachineStatusBorrow> machineStatusBorrows = new ArrayList<>();

        /**查询所有设备状态*/
        List<MachineStatus> machineStatuses;
        machineStatuses = machineStatusService.getByTag(accountId, regionId, tagIds);
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(accountUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(machineStatuses)) {
            return Collections.emptyList();
        }

        /**查询正在借用设备*/
        List<MachineBorrow> machineBorrows;
        if (CollUtil.isEmpty(regionId)) {
            machineBorrows = machineBorrowService.getByAccountId(accountId);
        } else {
            machineBorrows = machineBorrowService.getByRegionId(regionId);
        }
        List<Integer> machineBorrowsIds = machineBorrows.stream().map(MachineBorrow::getMachineId).collect(Collectors.toList());

        AccountConfigExt accountConfigExt = dataService.getAccountidExt(accountId + AccountConfigExtConstant.devicePriority);
        /**车辆功能优先级逻辑判断*/
        if (!machineBorrowsIds.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            List<Integer> delIdsMachine = devicePriorityService.checkPriority(machineBorrowsIds, accountId, DevicePriorityConstant.DEVICEPRIORITY_QXZ);
            machineBorrowsIds = machineBorrowsIds.stream().filter(machineStatus -> !delIdsMachine.contains(machineStatus)).collect(
                    Collectors.toList());
        }

        /**查询所有异常设备*/
        List<Integer> machineAbnormalMap;
        /**异常类型：车辆id*/
        Map<Integer, List<Integer>> machineAbnormalTypeMap = new HashMap<Integer, List<Integer>>();
        List<MachineAbnormal> machineAbnormals;
        if (CollUtil.isEmpty(regionId)) {
            machineAbnormals = machineAbnormalService.groupMachineIdAndType(accountId, null, null);
        } else {
            machineAbnormals = machineAbnormalService.groupMachineIdAndRegionId(regionId, null, null);
        }

        machineAbnormalMap = machineAbnormals.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toList());

        /**车辆功能优先级逻辑判断*/
        if (!machineAbnormals.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            machineAbnormalMap.clear();
            for (MachineAbnormal ma : machineAbnormals) {
                if (machineAbnormalTypeMap.containsKey(ma.getAbnormalType())) {
                    machineAbnormalTypeMap.get(ma.getAbnormalType()).add(ma.getMachineId());
                } else {
                    List<Integer> machineIds = new LinkedList<>();
                    machineIds.add(ma.getMachineId());
                    machineAbnormalTypeMap.put(ma.getAbnormalType(), machineIds);
                }
            }

            if (CollUtil.isNotEmpty(machineAbnormals)) {
                machineAbnormals = getAbnormalTypeDelMachineAbnormal(machineAbnormals, accountId, regionId);
                machineAbnormalMap = machineAbnormals.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toList());
            }
        }

        List<MachineFault> machineFaults;
        if (CollUtil.isEmpty(regionId)) {
            machineFaults = machineFaultService.getByAccountId(accountId);
        } else {
            machineFaults = machineFaultService.getByRegionId(regionId);
        }

        List<Integer> machineFaultsIds = machineFaults.stream().map(MachineFault::getMachineId).collect(Collectors.toList());
        //疑似故障
        /*List<Integer> suspectedFaultIdList = machineFaults.stream().filter(machineFault -> {
            return Objects.equals(machineFault.getFrom(), 4);
        }).map(MachineFault::getMachineId).collect(Collectors.toList());*/

        /**车辆功能优先级逻辑判断*/
        if (!machineFaults.isEmpty() && accountConfigExt != null && Integer.valueOf(accountConfigExt.getParamValue()).equals(1)) {
            machineFaultsIds.clear();
            /**返回数据*/
            List<MachineFault> faults = new ArrayList<>();
            List<MachineFault> ywFault = machineFaults.stream().filter(machineStatusFault -> machineStatusFault.getFrom() == 0).collect(
                    Collectors.toList());
            List<MachineFault> yhFault = machineFaults.stream().filter(machineStatusFault -> machineStatusFault.getFrom() == 1).collect(
                    Collectors.toList());
            /**运维异常校验*/
            List<Integer> ywMachineIds = ywFault.stream().map(MachineFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(ywMachineIds)) {
                List<Integer> delIds = devicePriorityService.checkPriority(ywMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YWGZ);
                ywFault = ywFault.stream().filter(machineStatus -> !delIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**用户异常校验*/
            List<Integer> yhMachineIds = yhFault.stream().map(MachineFault::getMachineId).collect(
                    Collectors.toList());
            if (CollUtil.isNotEmpty(ywMachineIds)) {
                List<Integer> yhdelIds = devicePriorityService.checkPriority(yhMachineIds, accountId,
                        DevicePriorityConstant.DEVICEPRIORITY_YHGZ);
                yhFault = yhFault.stream().filter(machineStatus -> !yhdelIds.contains(machineStatus.getMachineId())).collect(
                        Collectors.toList());
            }

            /**求并集*/
            faults.addAll(ywFault);
            faults.addAll(yhFault);
            machineFaultsIds = faults.stream().map(MachineFault::getMachineId).collect(Collectors.toList());
        }

        /**获取电池编号*/
        List<BatteryMachine> batteryMachineList;
        if (CollUtil.isEmpty(regionId)) {
            batteryMachineList = batteryMachineService.getByAccountId(accountId);
        } else {
            batteryMachineList = batteryMachineService.getByRegionIds(regionId);
        }
        Map<Integer, String> batteryMachineMap = new HashMap<>();
        for (BatteryMachine batteryMachine : batteryMachineList) {
            batteryMachineMap.put(batteryMachine.getMachineId(), batteryMachine.getBatterNO());
        }

        // 库存车辆
        List<StockMachine> stockMachines = stockMachineService.getByAccountId(accountId, regionId);
        List<Integer> stockMachineIds = stockMachines.stream().map(StockMachine::getMachineId).collect(Collectors.toList());

        // 扣押车辆
        List<DetentionMachineBound> detentionMachineBounds = detentionMachineBoundService.getListByAccount(accountId);
        List<Integer> detentionMachineMachineIds = detentionMachineBounds.stream().map(DetentionMachineBound::getMachineId).collect(Collectors.toList());

        for (MachineStatus ms : machineStatuses) {
            MachineStatusBorrow msb = new MachineStatusBorrow();

            /**是否使用中*/
            msb.setIsUse(machineBorrowsIds.contains(ms.getMachineId()));

            /**是否异常*/
            msb.setIsAbnormal(machineAbnormalMap.contains(ms.getMachineId()));

            /**是否故障*/
            msb.setIsFault(machineFaultsIds.contains(ms.getMachineId()));

            /** 库存状态 */
            msb.setStock(stockMachineIds.contains(ms.getMachineId()));

            /** 扣押状态 */
            msb.setDetention(detentionMachineMachineIds.contains(ms.getMachineId()));

            /**疑似故障*/
//            msb.setSuspectedFault(suspectedFaultIdList.contains(ms.getMachineId()));

            msb.setMachineId(ms.getMachineId());
            msb.setMachineNO(ms.getMachineNO());
            msb.setLon(ms.getLon());
            msb.setLat(ms.getLat());
            msb.setPosDt(ms.getPosDt());
            msb.setBatDt(ms.getBatDt());
            msb.setSocPercent(ms.getSocPercent());
            msb.setSurplusMileage(ms.getSurplusMileage());
            msb.setBatteryNO(batteryMachineMap.get(ms.getMachineId()));
            msb.setState(ms.getState());
            msb.setTagName(ms.getTagName());
            machineStatusBorrows.add(msb);
        }

        /**校准*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            calibrateService.celibrateMachineStatusBorrow(machineStatusBorrows, mapType);
        }

        /**查询设备编号和用户码*/
        if (CollUtil.isNotEmpty(machineStatusBorrows)) {
            List<Machine> machines = machineService.getByAccountId(accountId);
            Map<Integer, Machine> machineMap = new HashMap<Integer, Machine>();
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
            }

            for (MachineStatusBorrow ms : machineStatusBorrows) {
                Machine machine = machineMap.get(ms.getMachineId());
                if (machine != null) {
                    ms.setMachineNO(machine.getMachineNO());
                    ms.setUserCode(machine.getUserCode());
                    ms.setMachineType(machine.getMachineType());
                }
            }
        }

        return machineStatusBorrows;
    }

    @Override
    public List<MachineStatus> getLongTermNonPos(Integer accountId, List<Integer> regionId, Integer mapType, Integer hours) {
        AccountUser loginUser = LoginUserContextHolder.getLoginUser();
        if (CollUtil.isEmpty(regionId)) {
            regionId = georeGionService.getByAccountUserId(loginUser.getAccountUserId());
        }

        List<MachineStatus> machineStatuses = machineStatusService.getLongTermNonPos(accountId, regionId, hours);
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(loginUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }

        calibrateService.celibrateMachineStatus(machineStatuses, mapType);

        return machineStatuses;
    }

    @Override
    public List<MachineStatus> getLongOrder(Integer accountId, List<Integer> regionId, Integer mapType, Integer hours) {
        AccountUser loginUser = LoginUserContextHolder.getLoginUser();
        if (CollUtil.isEmpty(regionId)) {
            regionId = georeGionService.getByAccountUserId(loginUser.getAccountUserId());
        }

        List<MachineStatus> machineStatuses = machineStatusService.getLongOrder(accountId, regionId, hours);
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(loginUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }

        calibrateService.celibrateMachineStatus(machineStatuses, mapType);
        /*设置超时长订单时间*/
        if (CollectionUtil.isNotEmpty(machineStatuses)){
            Map<Integer, String> longOrderTime = getLongOrderTime(machineStatuses.stream().map(MachineStatus::getMachineId).collect(Collectors.toList()), accountId);
            if (CollectionUtil.isNotEmpty(longOrderTime)){
                for (MachineStatus ms : machineStatuses) {
                    ms.setLongOrderHour(longOrderTime.getOrDefault(ms.getMachineId(), ""));
                }
            }
        }
        return machineStatuses;
    }



    /**
     * 无订单
     * @param accountId 区域id
     * @param hours     小时
     * @param mapType   地图类型
     * @param regionId  分区id
     * @return  Result<List<MachineStatus>>
     */
    @Override
    public List<MachineStatus> getNoOrder(Integer accountId, Integer hours, Integer mapType, String regionId) {
        AccountUser loginUser = LoginUserContextHolder.getLoginUser();
        List<Integer> regionIdList;
        if (StrUtil.isBlank(regionId)) {
            regionIdList = georeGionService.getByAccountUserId(loginUser.getAccountUserId());
        }else {
            regionIdList = Arrays.stream(regionId.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
        }
        List<MachineStatus> machineStatuses = machineStatusService.getNoOrder(accountId, regionIdList, hours);
        //兼容监管
        List<Integer> superviseMachine = selectSuperviseMachine(loginUser.getAccountUserType(), accountId);
        if (CollUtil.isNotEmpty(superviseMachine)) {
            machineStatuses = machineStatuses.stream()
                    .filter(x -> superviseMachine.contains(x.getMachineId()))
                    .collect(Collectors.toList());
        }

        calibrateService.celibrateMachineStatus(machineStatuses, mapType);
        return machineStatuses;
    }


    /**
     * 查询超长时间订单
     * @param machineIdList 车辆列表
     * @param accountId 区域id
     */
    public Map<Integer, String> getLongOrderTime(List<Integer> machineIdList, Integer accountId){
        List<AccountConfigExt> paramKeys = accountConfigExtDao.getByParamKeys(accountId, Arrays.asList(AccountConfigExtConstant.LONG_ORDER_REMINDER_SWITCH, AccountConfigExtConstant.LONG_ORDER_REMINDER_TIME));
        if (CollectionUtil.isEmpty(paramKeys)) {
            return null;
        }

        /*根据设备id查询正在骑行中的数据，并校验大于配置的数据*/
        List<LongOrderTimeVO> machineBorrowList = machineBorrowService.getLongOrderTime(machineIdList);
        if (CollectionUtil.isNotEmpty(machineBorrowList)) {
            return machineBorrowList.stream().collect(Collectors.toMap(LongOrderTimeVO::getMachineId, LongOrderTimeVO::getLongTime));
        }
        return null;
    }


}
